<template>
  <div class="create-interview-container">
    <div class="header">
      <h1>{{ isEditMode ? '编辑职位与面试' : '创建新职位与面试' }}</h1>
      <p>{{ isEditMode ? `正在编辑职位: ${form.jobPosting.title}` : '配置一个新的招聘职位及其完整的面试流程' }}</p>
    </div>
    
    <el-form :model="form" ref="formRef" label-position="top" class="main-form">
      <el-card class="box-card">
          <template #header>
          <div class="card-header">
            <span>第一步：职位信息</span>
          </div>
          </template>
        
        <!-- 基本信息 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="职位名称" prop="jobPosting.title" :rules="[{ required: true, message: '请输入职位名称' }]">
              <el-input v-model="form.jobPosting.title" placeholder="例如：高级前端工程师" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所属部门" prop="jobPosting.department" :rules="[{ required: true, message: '请输入所属部门' }]">
              <el-input v-model="form.jobPosting.department" placeholder="例如：技术研发部" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="工作地点" prop="jobPosting.location" :rules="[{ required: true, message: '请选择工作地点' }]">
              <el-select v-model="form.jobPosting.location" placeholder="请选择工作地点" style="width: 100%">
                <el-option label="北京" value="北京" />
                <el-option label="上海" value="上海" />
                <el-option label="深圳" value="深圳" />
                <el-option label="杭州" value="杭州" />
                <el-option label="广州" value="广州" />
                <el-option label="成都" value="成都" />
                <el-option label="远程办公" value="远程" />
                <el-option label="其他" value="其他" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="雇佣类型" prop="jobPosting.employment_type" :rules="[{ required: true, message: '请选择雇佣类型' }]">
              <el-select v-model="form.jobPosting.employment_type" placeholder="请选择雇佣类型" style="width: 100%">
                <el-option label="全职" value="full_time" />
                <el-option label="兼职" value="part_time" />
                <el-option label="实习" value="internship" />
                <el-option label="合同工" value="contract" />
                <el-option label="远程工作" value="remote" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 任职要求 -->
        <el-divider content-position="left">任职要求</el-divider>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="学历要求" prop="jobPosting.education" :rules="[{ required: true, message: '请输入学历要求' }]">
              <el-input v-model="form.jobPosting.education" placeholder="例如：本科及以上学历，985/211优先" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="工作经验" prop="jobPosting.working_experience" :rules="[{ required: true, message: '请输入工作经验要求' }]">
              <el-input v-model="form.jobPosting.working_experience" placeholder="例如：3-5年相关工作经验" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="技能要求" prop="jobPosting.requirements_skills" :rules="[{ required: true, message: '请输入技能要求' }]">
          <el-input v-model="form.jobPosting.requirements_skills" type="textarea" :rows="3" 
            placeholder="请详细描述所需的技术技能，例如：精通JavaScript、React、Node.js等前端技术栈..." />
        </el-form-item>

        <el-form-item label="软技能要求" prop="jobPosting.soft_skills" :rules="[{ required: true, message: '请输入软技能要求' }]">
          <el-input v-model="form.jobPosting.soft_skills" type="textarea" :rows="2" 
            placeholder="请描述所需的软技能，例如：良好的沟通能力、团队合作精神、学习能力强..." />
        </el-form-item>

        <!-- 薪资福利 -->
        <el-divider content-position="left">薪资福利</el-divider>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="薪资范围" prop="jobPosting.salary_range" :rules="[{ required: true, message: '请输入薪资范围' }]">
              <el-input v-model="form.jobPosting.salary_range" placeholder="例如：15k-25k 或 面议" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="招聘人数" prop="jobPosting.number_of_hires">
              <el-input-number v-model="form.jobPosting.number_of_hires" :min="1" :max="50" 
                placeholder="请输入招聘人数" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="福利待遇" prop="jobPosting.benefits" :rules="[{ required: true, message: '请输入福利待遇' }]">
          <el-input v-model="form.jobPosting.benefits" type="textarea" :rows="3" 
            placeholder="请描述福利待遇，例如：五险一金、年终奖、股票期权、技术培训、弹性工作时间..." />
        </el-form-item>

        <!-- 其他信息 -->
        <el-divider content-position="left">其他信息</el-divider>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="联系邮箱" prop="jobPosting.contact_email">
              <el-input v-model="form.jobPosting.contact_email" placeholder="例如：hr@company.com" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="申请截止时间" prop="jobPosting.application_deadline">
              <el-date-picker v-model="form.jobPosting.application_deadline" type="datetime" 
                placeholder="选择截止时间" style="width: 100%" format="YYYY-MM-DD HH:mm:ss" 
                value-format="YYYY-MM-DDTHH:mm:ss.000Z" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="匹配度阈值" prop="jobPosting.required_match_score">
              <el-slider v-model="form.jobPosting.required_match_score" :min="0" :max="100" 
                show-input :format-tooltip="(val) => `${val}%`" />
              <div class="form-help-text">
                简历匹配度达到此分数才能通过初筛，建议设置为 60-80%
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="职位状态" prop="jobPosting.is_active">
              <el-switch v-model="form.jobPosting.is_active" active-text="招聘中" inactive-text="已关闭" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="职位描述 (JD)" prop="jobPosting.description" :rules="[{ required: true, message: '请输入职位描述' }]">
          <el-input v-model="form.jobPosting.description" type="textarea" :rows="6" 
            placeholder="请详细描述职位职责、工作内容、发展前景等..." />
        </el-form-item>
        </el-card>
        
      <el-card class="box-card">
          <template #header>
          <div class="card-header">
            <span>第二步：配置面试模板</span>
            <el-button @click="refreshQuestions" :loading="questionsLoading" size="small">
              <el-icon><Refresh /></el-icon>
              刷新题库
            </el-button>
          </div>
          </template>
          
        <el-form-item label="面试模板标题" prop="interviewTemplate.title" :rules="[{ required: true, message: '请输入面试模板标题' }]">
          <el-input v-model="form.interviewTemplate.title" placeholder="例如：T3级前端岗标准面试" />
                  </el-form-item>
                  
        <!-- 题库加载状态 -->
        <div v-if="questionsLoading" class="loading-section">
          <el-skeleton :rows="3" animated />
          <p class="loading-text">正在加载题库...</p>
                </div>
                
        <!-- 题库为空时的提示 -->
        <div v-else-if="allLogistQuestions.length === 0 && allVideoQuestions.length === 0" class="empty-questions">
          <el-empty description="题库暂无数据">
            <div class="empty-actions">
              <el-button @click="$router.push('/hr/question-bank')" type="primary">
                前往题库管理
                      </el-button>
              <el-button @click="createMockData" type="success">
                使用演示数据
                        </el-button>
            </div>
          </el-empty>
          </div>
        
        <div v-else>
          <!-- 逻辑题选择 -->
          <el-form-item label="选择逻辑题">
            <div class="question-stats">
              <el-tag>可选题目：{{ allLogistQuestions.length }}</el-tag>
              <el-tag type="success">已选：{{ form.interviewTemplate.logist_question_ids.length }}</el-tag>
            </div>
            <el-transfer
              v-model="form.interviewTemplate.logist_question_ids"
              :data="allLogistQuestions"
              :titles="['逻辑题库', '已选题目']"
              :props="{ key: 'id', label: 'displayLabel' }"
              filterable
              :filter-method="filterLogistQuestions"
              class="question-transfer"
            />
          </el-form-item>
        
          <!-- 视频题选择 -->
          <el-form-item label="选择视频题">
            <div class="question-stats">
              <el-tag>可选题目：{{ allVideoQuestions.length }}</el-tag>
              <el-tag type="success">已选：{{ form.interviewTemplate.video_question_ids.length }}</el-tag>
            </div>
            <el-transfer
              v-model="form.interviewTemplate.video_question_ids"
              :data="allVideoQuestions"
              :titles="['视频题库', '已选题目']"
              :props="{ key: 'id', label: 'displayLabel' }"
              filterable
              :filter-method="filterVideoQuestions"
              class="question-transfer"
            />
          </el-form-item>
        </div>
      </el-card>

      <!-- 第三步：面试权重配置 -->
      <el-card class="box-card">
        <template #header>
          <div class="card-header">
            <span>第三步：面试权重配置</span>
            <el-tag :type="weightSum === 1.0 ? 'success' : 'danger'">
              权重总和: {{ (weightSum * 100).toFixed(0) }}%
            </el-tag>
          </div>
        </template>

        <div class="weight-config">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="简历匹配权重" prop="interviewTemplate.resume_match_weight">
                <el-slider
                  v-model="form.interviewTemplate.resume_match_weight"
                  :min="0"
                  :max="1"
                  :step="0.05"
                  show-input
                  :format-tooltip="(val) => `${(val * 100).toFixed(0)}%`"
                  @change="validateWeights"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="专业技能权重" prop="interviewTemplate.professional_skill_weight">
                <el-slider
                  v-model="form.interviewTemplate.professional_skill_weight"
                  :min="0"
                  :max="1"
                  :step="0.05"
                  show-input
                  :format-tooltip="(val) => `${(val * 100).toFixed(0)}%`"
                  @change="validateWeights"
                />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="逻辑思维能力权重" prop="interviewTemplate.logical_thinking_weight">
                <el-slider
                  v-model="form.interviewTemplate.logical_thinking_weight"
                  :min="0"
                  :max="1"
                  :step="0.05"
                  show-input
                  :format-tooltip="(val) => `${(val * 100).toFixed(0)}%`"
                  @change="validateWeights"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="创新能力权重" prop="interviewTemplate.innovation_weight">
                <el-slider
                  v-model="form.interviewTemplate.innovation_weight"
                  :min="0"
                  :max="1"
                  :step="0.05"
                  show-input
                  :format-tooltip="(val) => `${(val * 100).toFixed(0)}%`"
                  @change="validateWeights"
                />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="压力应对权重" prop="interviewTemplate.stress_management_weight">
                <el-slider
                  v-model="form.interviewTemplate.stress_management_weight"
                  :min="0"
                  :max="1"
                  :step="0.05"
                  show-input
                  :format-tooltip="(val) => `${(val * 100).toFixed(0)}%`"
                  @change="validateWeights"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="语言能力权重" prop="interviewTemplate.expression_weight">
                <el-slider
                  v-model="form.interviewTemplate.expression_weight"
                  :min="0"
                  :max="1"
                  :step="0.05"
                  show-input
                  :format-tooltip="(val) => `${(val * 100).toFixed(0)}%`"
                  @change="validateWeights"
                />
              </el-form-item>
            </el-col>
          </el-row>

          <div class="weight-validation" :class="{ 'is-valid': weightSum === 1.0, 'is-invalid': weightSum !== 1.0 }">
            <el-alert
              v-if="weightSum !== 1.0"
              title="权重配置提示"
              type="warning"
              :closable="false"
              show-icon
            >
              <template #default>
                <p>6个权重项的总和必须等于100%，当前总和为 {{ (weightSum * 100).toFixed(0) }}%</p>
                <p>建议调整权重分配，确保总和为100%</p>
              </template>
            </el-alert>
            <el-alert
              v-else
              title="权重配置完成"
              type="success"
              :closable="false"
              show-icon
            >
              <template #default>
                <p>权重配置正确，总和为100%</p>
              </template>
            </el-alert>
          </div>
        </div>
      </el-card>

      <!-- 第四步：语音配置 -->
      <el-card class="box-card">
        <template #header>
          <div class="card-header">
            <span>第四步：语音配置</span>
            <el-button @click="loadVoiceProfiles" :loading="voiceProfilesLoading" size="small">
              <el-icon><Refresh /></el-icon>
              刷新语音配置
            </el-button>
          </div>
        </template>

        <div v-if="voiceProfilesLoading" class="loading-section">
          <el-skeleton :rows="2" animated />
          <p class="loading-text">正在加载语音配置...</p>
        </div>

        <div v-else-if="voiceProfiles.length === 0" class="empty-voice-profiles">
          <el-empty description="暂无可用语音配置">
            <el-button type="primary" @click="loadVoiceProfiles">
              重新加载
            </el-button>
          </el-empty>
        </div>

        <div v-else class="voice-config">
          <el-form-item label="默认语音配置" prop="interviewTemplate.default_voice_profile">
            <el-select
              v-model="form.interviewTemplate.default_voice_profile"
              placeholder="请选择默认语音配置"
              style="width: 100%"
            >
              <el-option
                v-for="profile in voiceProfiles"
                :key="profile.id"
                :label="profile.name"
                :value="profile.id"
              >
                <div class="voice-option">
                  <span class="voice-name">{{ profile.name }}</span>
                  <span class="voice-desc">{{ profile.description }}</span>
                </div>
              </el-option>
            </el-select>
            <div class="form-help-text">
              选择面试题目朗读的默认语音配置，候选人可以在面试过程中切换语音
            </div>
          </el-form-item>

          <div class="voice-preview">
            <h4>语音配置预览</h4>
            <div class="voice-profiles-grid">
              <div
                v-for="profile in voiceProfiles"
                :key="profile.id"
                class="voice-profile-card"
                :class="{ 'is-selected': form.interviewTemplate.default_voice_profile === profile.id }"
              >
                <div class="voice-profile-header">
                  <span class="voice-type">{{ profile.voice_type }}</span>
                  <el-tag :type="profile.is_active ? 'success' : 'info'" size="small">
                    {{ profile.is_active ? '可用' : '不可用' }}
                  </el-tag>
                </div>
                <div class="voice-profile-content">
                  <h5>{{ profile.name }}</h5>
                  <p>{{ profile.description }}</p>
                  <div class="voice-params">
                    <span>语速: {{ profile.speed }}x</span>
                    <span>音调: {{ profile.pitch }}x</span>
                    <span>音量: {{ profile.volume }}x</span>
                  </div>
                </div>
                <div class="voice-profile-actions">
                  <el-button
                    v-if="profile.is_active"
                    size="small"
                    @click="testVoice(profile)"
                    :loading="testingVoice === profile.id"
                  >
                    试听
                  </el-button>
                </div>
              </div>
            </div>
          </div>
        </div>
      </el-card>
      </el-form>

    <div class="footer-actions">
      <el-button @click="router.back()">返回</el-button>
      <el-button type="primary" @click="handleSubmit" :loading="isSubmitting">
        {{ isEditMode ? '保存更改' : '创建职位与面试' }}
      </el-button>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import { Refresh } from '@element-plus/icons-vue';
import { businessApi as api } from '@/services/api';
import { useAuthStore } from '@/stores/auth';

const route = useRoute();
const router = useRouter();
const authStore = useAuthStore();

const isEditMode = computed(() => !!route.params.id);
const isSubmitting = ref(false);
const questionsLoading = ref(false);
const voiceProfilesLoading = ref(false);
const testingVoice = ref(null);

const form = ref({
  jobPosting: {
    title: '',
    department: '',
    location: '',
    employment_type: '',
    education: '',
    working_experience: '',
    requirements_skills: '',
    soft_skills: '',
    description: '',
    number_of_hires: 1,
    salary_range: '',
    benefits: '',
    contact_email: '',
    application_deadline: null,
    required_match_score: 70,
    is_active: true,
  },
  interviewTemplate: {
    title: '',
    logist_question_ids: [],
    video_question_ids: [],
    // 权重配置 - 默认值总和为1.0
    resume_match_weight: 0.25,
    professional_skill_weight: 0.20,
    logical_thinking_weight: 0.15,
    innovation_weight: 0.15,
    stress_management_weight: 0.15,
    expression_weight: 0.10,
    // 语音配置
    default_voice_profile: null,
  },
});

const allLogistQuestions = ref([]);
const allVideoQuestions = ref([]);
const voiceProfiles = ref([]);

// 处理题目数据格式
const processLogistQuestions = (questions) => {
  return questions.map(q => ({
    id: q.id,
    displayLabel: `${q.title || q.question_id || `Q${q.id}`} - ${(q.stem || q.content || '').substring(0, 50)}...`,
    stem: q.stem || q.content || '',
    topic: q.topic || '未分类',
    question_type: q.question_type || 1,
    score: q.score || 1
  }));
};

const processVideoQuestions = (questions) => {
  return questions.map(q => ({
    id: q.id,
    displayLabel: `V${q.id} - ${(q.content || '').substring(0, 50)}...`,
    content: q.content || '',
    topic_tags: q.topic_tags || '',
    created_by_name: q.created_by_name || ''
  }));
};

// 题目筛选方法
const filterLogistQuestions = (query, item) => {
  return item.displayLabel.toLowerCase().includes(query.toLowerCase()) ||
         item.stem.toLowerCase().includes(query.toLowerCase()) ||
         item.topic.toLowerCase().includes(query.toLowerCase());
};

const filterVideoQuestions = (query, item) => {
  return item.displayLabel.toLowerCase().includes(query.toLowerCase()) ||
         item.content.toLowerCase().includes(query.toLowerCase()) ||
         item.topic_tags.toLowerCase().includes(query.toLowerCase());
};

const fetchAllQuestions = async () => {
  questionsLoading.value = true;
  try {
    console.log('开始加载题库...');
    
    // 并行加载两种类型的题目
    const [logistResult, videoResult] = await Promise.all([
      api.getLogistQuestions(1, 100).catch(err => {
        console.warn('加载逻辑题失败:', err);
        return { results: [], data: [] };
      }),
      api.getVideoQuestions(1, 100).catch(err => {
        console.warn('加载视频题失败:', err);
        return { results: [], data: [] };
      })
    ]);

    console.log('逻辑题API响应:', logistResult);
    console.log('视频题API响应:', videoResult);

    // 处理逻辑题数据
    let logistQuestions = [];
    if (logistResult.results && Array.isArray(logistResult.results)) {
      logistQuestions = logistResult.results;
    } else if (logistResult.data && Array.isArray(logistResult.data)) {
      logistQuestions = logistResult.data;
    } else if (Array.isArray(logistResult)) {
      logistQuestions = logistResult;
    }

    // 处理视频题数据
    let videoQuestions = [];
    if (videoResult.results && Array.isArray(videoResult.results)) {
      videoQuestions = videoResult.results;
    } else if (videoResult.data && Array.isArray(videoResult.data)) {
      videoQuestions = videoResult.data;
    } else if (Array.isArray(videoResult)) {
      videoQuestions = videoResult;
    }

    allLogistQuestions.value = processLogistQuestions(logistQuestions);
    allVideoQuestions.value = processVideoQuestions(videoQuestions);

    console.log('处理后的逻辑题:', allLogistQuestions.value.length);
    console.log('处理后的视频题:', allVideoQuestions.value.length);

    if (allLogistQuestions.value.length === 0 && allVideoQuestions.value.length === 0) {
      ElMessage.warning('题库暂无数据，请先在题库管理中添加题目');
    } else {
      ElMessage.success(`题库加载成功：逻辑题${allLogistQuestions.value.length}个，视频题${allVideoQuestions.value.length}个`);
    }
  } catch (error) {
    console.error('加载题库失败:', error);
    ElMessage.error('加载题库失败，请检查网络连接');
  } finally {
    questionsLoading.value = false;
  }
};

const refreshQuestions = () => {
  fetchAllQuestions();
};

// 权重总和计算
const weightSum = computed(() => {
  const weights = [
    form.value.interviewTemplate.resume_match_weight,
    form.value.interviewTemplate.professional_skill_weight,
    form.value.interviewTemplate.logical_thinking_weight,
    form.value.interviewTemplate.innovation_weight,
    form.value.interviewTemplate.stress_management_weight,
    form.value.interviewTemplate.expression_weight
  ];
  return weights.reduce((sum, weight) => sum + weight, 0);
});

// 权重验证
const validateWeights = () => {
  if (Math.abs(weightSum.value - 1.0) > 0.01) {
    ElMessage.warning(`权重总和为 ${(weightSum.value * 100).toFixed(0)}%，建议调整为100%`);
  }
};

// 加载语音配置
const loadVoiceProfiles = async () => {
  voiceProfilesLoading.value = true;
  try {
    // TODO: 暂时注释掉voiceApi调用，等后端API就绪后恢复
    // const response = await voiceApi.getVoiceProfiles();
    // voiceProfiles.value = response.results || response.data || response || [];
    
    // 临时使用模拟数据
    voiceProfiles.value = [
      { id: 1, name: '标准女声', language: 'zh-CN', is_active: true },
      { id: 2, name: '标准男声', language: 'zh-CN', is_active: true }
    ];
    
    if (voiceProfiles.value.length > 0 && !form.value.interviewTemplate.default_voice_profile) {
      // 默认选择第一个可用的语音配置
      const firstActive = voiceProfiles.value.find(p => p.is_active);
      if (firstActive) {
        form.value.interviewTemplate.default_voice_profile = firstActive.id;
      }
    }
    
    ElMessage.success(`加载了 ${voiceProfiles.value.length} 个语音配置`);
  } catch (error) {
    console.error('加载语音配置失败:', error);
    ElMessage.error('加载语音配置失败');
  } finally {
    voiceProfilesLoading.value = false;
  }
};

// 测试语音
const testVoice = async (profile) => {
  testingVoice.value = profile.id;
  try {
    // 这里可以添加语音测试逻辑
    ElMessage.info(`正在测试语音: ${profile.name}`);
    // 实际实现中，这里会调用语音合成API
    await new Promise(resolve => setTimeout(resolve, 2000));
    ElMessage.success(`语音测试完成: ${profile.name}`);
  } catch (error) {
    console.error('语音测试失败:', error);
    ElMessage.error('语音测试失败');
  } finally {
    testingVoice.value = null;
  }
};

// 创建演示数据
const createMockData = () => {
  // 模拟逻辑题数据
  const mockLogistQuestions = [
      { 
        id: 1, 
      displayLabel: 'Q001 - 逻辑推理：以下哪个选项最符合逻辑？',
      stem: '以下哪个选项最符合逻辑？',
      topic: '逻辑推理题',
      question_type: 1,
      score: 2
      },
      { 
        id: 2, 
      displayLabel: 'Q002 - 数学运算：计算以下表达式的值',
      stem: '计算以下表达式的值：(2+3)×4-5',
      topic: '数学运算',
      question_type: 1,
      score: 3
      },
      { 
        id: 3, 
      displayLabel: 'Q003 - 图形推理：找出图形规律',
      stem: '根据图形规律，选择下一个图形',
      topic: '图形推理题',
      question_type: 1,
      score: 2
    }
  ];

  // 模拟视频题数据
  const mockVideoQuestions = [
      {
        id: 1,
      displayLabel: 'V001 - 请介绍一下您的项目经验',
      content: '请详细介绍一下您最近参与的一个项目，包括您的角色、遇到的挑战以及解决方案。',
      topic_tags: '项目经验,技术能力',
      created_by_name: '系统'
      },
      {
        id: 2,
      displayLabel: 'V002 - 描述您的职业规划',
      content: '请描述一下您未来3-5年的职业规划，以及为什么选择我们公司。',
      topic_tags: '职业规划,动机',
      created_by_name: '系统'
      },
      {
        id: 3,
      displayLabel: 'V003 - 团队协作经验分享',
      content: '请分享一次您在团队中解决冲突或协调合作的经历。',
      topic_tags: '团队协作,沟通能力',
      created_by_name: '系统'
    }
  ];

  allLogistQuestions.value = mockLogistQuestions;
  allVideoQuestions.value = mockVideoQuestions;
  
  ElMessage.info('已加载演示数据，您可以使用这些题目来测试面试创建功能');
};

const fetchExistingData = async () => {
  const jobId = route.params.id;
  if (!jobId) return;

  try {
    const jobRes = await api.getJobPosting(jobId);
    form.value.jobPosting = jobRes.data || jobRes;
    
    // 如果职位有关联的模板，则获取模板信息
    if (jobRes.data?.interview_template || jobRes.interview_template) {
      const template = jobRes.data?.interview_template || jobRes.interview_template;
      const templateId = template.id;
      const templateRes = await api.getInterviewTemplate(templateId);
      const templateData = templateRes.data || templateRes;
      
      form.value.interviewTemplate = {
        id: templateData.id,
        title: templateData.title,
        logist_question_ids: templateData.logist_questions?.map(q => q.id) || [],
        video_question_ids: templateData.video_questions?.map(q => q.id) || [],
      };
    } else {
      // 如果没有模板，但仍在编辑职位，可以默认一个模板标题
      form.value.interviewTemplate.title = `${form.value.jobPosting.title} - 面试流程`;
    }
  } catch (error) {
    console.error('获取现有数据失败:', error);
    ElMessage.error('获取现有数据失败');
    router.push({ name: 'InterviewManagement' });
  }
};

const handleSubmit = async () => {
  // 表单验证
  if (!form.value.jobPosting.title || !form.value.jobPosting.description) {
    ElMessage.error('请填写完整的职位信息');
    return;
  }
  
  if (!form.value.interviewTemplate.title) {
    ElMessage.error('请填写面试模板标题');
    return;
  }

  // 权重验证
  if (Math.abs(weightSum.value - 1.0) > 0.01) {
    ElMessage.error(`权重总和必须为100%，当前为 ${(weightSum.value * 100).toFixed(0)}%`);
    return;
  }

  // 用户验证
  console.log('当前认证状态:', {
    isAuthenticated: authStore.isAuthenticated,
    token: authStore.token ? '有token' : '无token',
    user: authStore.user,
    userRole: authStore.userRole
  });
  
  if (!authStore.user || !authStore.user.id) {
    console.error('用户信息异常 - 详细信息:', {
      user: authStore.user,
      userId: authStore.user?.id,
      token: authStore.token,
      isAuthenticated: authStore.isAuthenticated,
      localStorage_token: localStorage.getItem('auth_token'),
      localStorage_role: localStorage.getItem('user_role')
    });
    
    // 临时修复：如果有token但没有用户信息，尝试重建
    const storedToken = localStorage.getItem('auth_token');
    const storedRole = localStorage.getItem('user_role');
    
    if (storedToken && storedRole && !authStore.user) {
      console.log('尝试重建用户信息...');
      // 创建临时用户信息
      authStore.user = {
        id: 1, // 临时ID
        name: storedRole === 'hr' ? 'HR用户' : '候选人用户',
        email: 'temp@example.com',
        role: storedRole
      };
      authStore.token = storedToken;
      authStore.userRole = storedRole;
      
      console.log('重建的用户信息:', authStore.user);
    } else {
      ElMessage.error('用户信息异常，请重新登录');
      return;
    }
  }

  isSubmitting.value = true;
  try {
    let jobPostingResponse;
    
    // Step 1: Create or Update Job Posting
    const jobPostingData = {
      ...form.value.jobPosting,
      created_by: authStore.user.id // 添加 created_by 参数
    };
    
    // 数据清理 - 移除空字符串，确保数据类型正确
    Object.keys(jobPostingData).forEach(key => {
      if (jobPostingData[key] === '' || jobPostingData[key] === null) {
        delete jobPostingData[key]; // 删除空字符串和null字段
      }
    });
    
    // 确保数值字段为数字类型
    if (jobPostingData.number_of_hires) {
      jobPostingData.number_of_hires = Number(jobPostingData.number_of_hires);
    }
    if (jobPostingData.required_match_score) {
      jobPostingData.required_match_score = Number(jobPostingData.required_match_score);
    }
    
    // 确保布尔字段为布尔类型
    if (jobPostingData.is_active !== undefined) {
      jobPostingData.is_active = Boolean(jobPostingData.is_active);
    }
    
    // 处理日期字段
    if (jobPostingData.application_deadline && jobPostingData.application_deadline instanceof Date) {
      jobPostingData.application_deadline = jobPostingData.application_deadline.toISOString().split('T')[0]; // 转换为YYYY-MM-DD格式
    }
    
    console.log('清理后的JobPosting数据:', jobPostingData);
    console.log('用户信息:', authStore.user);
    
    if (isEditMode.value) {
      jobPostingResponse = await api.updateJobPosting(route.params.id, jobPostingData);
    } else {
      jobPostingResponse = await api.createJobPosting(jobPostingData);
    }
    
    // 处理不同的响应结构
    let jobPostingResponseData = jobPostingResponse.data || jobPostingResponse;
    
    // 如果响应包含success字段，则取data字段
    if (jobPostingResponseData.success && jobPostingResponseData.data) {
      jobPostingResponseData = jobPostingResponseData.data;
    }
    
    const jobPostingId = jobPostingResponseData.id || (isEditMode.value ? route.params.id : null);
    
    if (!jobPostingId) {
      throw new Error('无法获取职位ID，响应数据结构异常');
    }

    // Step 2: Create or Update Interview Template
    const templatePayload = {
      title: form.value.interviewTemplate.title,
      description: form.value.interviewTemplate.description || '',
      job_posting: jobPostingId,
      logist_questions: form.value.interviewTemplate.logist_question_ids,
      video_questions: form.value.interviewTemplate.video_question_ids,
      // 权重配置
      resume_match_weight: form.value.interviewTemplate.resume_match_weight,
      professional_skill_weight: form.value.interviewTemplate.professional_skill_weight,
      logical_thinking_weight: form.value.interviewTemplate.logical_thinking_weight,
      innovation_weight: form.value.interviewTemplate.innovation_weight,
      stress_management_weight: form.value.interviewTemplate.stress_management_weight,
      expression_weight: form.value.interviewTemplate.expression_weight,
      created_by: authStore.user.id, // 添加 created_by 参数
    };
    
    // 语音配置 - 只有当选择了语音配置时才添加
    if (form.value.interviewTemplate.default_voice_profile) {
      templatePayload.default_voice_profile = Number(form.value.interviewTemplate.default_voice_profile);
    }
    
    // 数据清理 - 移除空字符串和null值
    Object.keys(templatePayload).forEach(key => {
      if (templatePayload[key] === '' || templatePayload[key] === null) {
        delete templatePayload[key];
      }
    });
    
    console.log('清理后的InterviewTemplate数据:', templatePayload);
    
    let templateResponse;
    if (form.value.interviewTemplate.id) {
      templateResponse = await api.updateInterviewTemplate(form.value.interviewTemplate.id, templatePayload);
    } else {
      templateResponse = await api.createInterviewTemplate(templatePayload);
    }

    ElMessage.success(isEditMode.value ? '更新成功！' : '创建成功！');
    
    // 添加短暂延迟确保后端数据已完全写入，然后跳转
    setTimeout(() => {
      router.push({ name: 'InterviewManagement' });
    }, 500);
  } catch (error) {
    console.error('提交失败:', error);
    console.error('错误详情:', error.response?.data);
    
    // 处理400错误的详细信息
    if (error.response?.status === 400) {
      const errorData = error.response.data;
      console.error('400错误详细信息:', errorData);
      
      // 尝试提取具体的字段错误
      if (typeof errorData === 'object') {
        const fieldErrors = [];
        for (const [field, messages] of Object.entries(errorData)) {
          if (Array.isArray(messages)) {
            fieldErrors.push(`${field}: ${messages.join(', ')}`);
          } else if (typeof messages === 'string') {
            fieldErrors.push(`${field}: ${messages}`);
          }
        }
        
        if (fieldErrors.length > 0) {
          ElMessage.error(`参数错误: ${fieldErrors.join('; ')}`);
          return;
        }
      }
    }
    
    const errorMessage = error.response?.data?.message || error.message || '操作失败，请检查输入';
    ElMessage.error(errorMessage);
  } finally {
    isSubmitting.value = false;
  }
};

onMounted(async () => {
  await fetchAllQuestions();
  await loadVoiceProfiles();
  if (isEditMode.value) {
    await fetchExistingData();
    }
});
</script>

<style scoped>
.create-interview-container {
  padding: 2rem;
  max-width: 1200px;
  margin: 0 auto;
}

.header {
  margin-bottom: 2rem;
}

.header h1 {
  color: #333;
  margin-bottom: 0.5rem;
}

.header p {
  color: #666;
  font-size: 14px;
}

.box-card {
  margin-bottom: 2rem;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: 600;
  color: #333;
}

.loading-section {
  text-align: center;
  padding: 2rem;
}

.loading-text {
  color: #666;
  margin-top: 1rem;
}

.empty-questions {
  text-align: center;
  padding: 2rem;
}

.empty-actions {
  display: flex;
  gap: 12px;
  justify-content: center;
  margin-top: 16px;
}

.question-stats {
  display: flex;
  gap: 8px;
  margin-bottom: 16px;
}

.question-transfer {
  width: 100%;
}

.question-transfer :deep(.el-transfer-panel) {
  width: 45%;
}

.weight-config {
  padding: 20px 0;
}

.weight-validation {
  margin-top: 20px;
}

.weight-validation.is-valid {
  border-left: 4px solid #67c23a;
}

.weight-validation.is-invalid {
  border-left: 4px solid #f56c6c;
}

.voice-config {
  padding: 20px 0;
}

.empty-voice-profiles {
  text-align: center;
  padding: 2rem;
}

.voice-preview {
  margin-top: 20px;
}

.voice-preview h4 {
  margin-bottom: 16px;
  color: #333;
}

.voice-profiles-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 16px;
}

.voice-profile-card {
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  padding: 16px;
  transition: all 0.3s;
}

.voice-profile-card:hover {
  border-color: #409eff;
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.1);
}

.voice-profile-card.is-selected {
  border-color: #409eff;
  background-color: #f0f9ff;
}

.voice-profile-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.voice-type {
  font-size: 12px;
  color: #666;
  background-color: #f5f5f5;
  padding: 2px 8px;
  border-radius: 4px;
}

.voice-profile-content h5 {
  margin: 0 0 8px 0;
  color: #333;
}

.voice-profile-content p {
  margin: 0 0 12px 0;
  color: #666;
  font-size: 14px;
}

.voice-params {
  display: flex;
  gap: 12px;
  font-size: 12px;
  color: #999;
}

.voice-profile-actions {
  margin-top: 12px;
  text-align: right;
}

.voice-option {
  display: flex;
  flex-direction: column;
}

.voice-name {
  font-weight: 500;
  color: #333;
}

.voice-desc {
  font-size: 12px;
  color: #666;
  margin-top: 2px;
}

.form-help-text {
  font-size: 12px;
  color: #999;
  margin-top: 4px;
}

.footer-actions {
  text-align: right;
  margin-top: 2rem;
  padding-top: 2rem;
  border-top: 1px solid #eee;
}

.footer-actions .el-button {
  margin-left: 12px;
}

/* 新增样式 */
.form-help-text {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
  line-height: 1.4;
}

.el-divider {
  margin: 24px 0 16px 0;
}

.el-divider__text {
  font-weight: 600;
  color: #409eff;
}

.box-card {
  margin-bottom: 20px;
}

.box-card .el-card__body {
  padding: 24px;
}

@media (max-width: 768px) {
  .create-interview-container {
    padding: 16px;
  }
  
  .el-col {
    margin-bottom: 16px;
  }
  
  .footer-actions {
    text-align: center;
  }
  
  .footer-actions .el-button {
    margin: 0 6px 8px 6px;
  }
}
</style> 